package com.congee02.dbservlet.listener;

import com.congee02.dbservlet.framework.ioc.container.SimpleAnnotationApplicationContext;
import com.congee02.dbservlet.framework.ioc.servlet.MappingHttpServlet;
import com.congee02.dbservlet.ioc.SingletonIoCContainer;
import com.congee02.dbservlet.service.register.RegisterServiceImpl;
import com.congee02.dbservlet.servlet.LoginServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRegistration;
import javax.servlet.http.HttpServlet;
import java.util.List;

public class IoCContainerContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        SimpleAnnotationApplicationContext applicationContext = SingletonIoCContainer.get();
        List<MappingHttpServlet> servlets = applicationContext.getHttpServlets();
        for (MappingHttpServlet servlet : servlets) {
            addServletAndMappings(servlet.getServletName(), servletContext, servlet.getHttpServlet(), servlet.getMappings());
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }

    private static void addServletAndMappings(String servletName, ServletContext servletContext, HttpServlet servlet, String... mappings) {
        ServletRegistration.Dynamic dynamic = servletContext.addServlet(servletName, servlet);
        for (String mapping : mappings) {
            dynamic.addMapping(mapping);
        }
    }

    public static void main(String[] args) {
        SimpleAnnotationApplicationContext applicationContext = SingletonIoCContainer.get();
        System.out.println(applicationContext.getBean(RegisterServiceImpl.class));
    }


}
